{% extends 'admin/base.html' %}
{% set active_page = 'members' %}

{% block title %}会员管理{% endblock %}

{% block page_title %}会员管理{% endblock %}

{% block page_subtitle %}管理会员信息、权限配置和续费提醒{% endblock %}

{% block content %}
<div class="content-scroll">
<!-- 会员统计卡片 -->
    <div class="row mb-4">
        <div class="col-lg-2 col-md-4 mb-3">
            <div class="metric-card">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <div class="text-secondary">
                        <i class="bi bi-people" style="font-size: 2rem;"></i>
                    </div>
                    <div class="text-end">
                        <h4 class="mb-0" id="basicMembersCount">{{ stats.basic_members }}</h4>
                        <small class="text-muted">基础会员</small>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-2 col-md-4 mb-3">
            <div class="metric-card">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <div class="text-primary">
                        <i class="bi bi-star" style="font-size: 2rem;"></i>
                    </div>
                    <div class="text-end">
                        <h4 class="mb-0" id="professionalMembersCount">{{ stats.professional_members }}</h4>
                        <small class="text-muted">专业会员</small>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-2 col-md-4 mb-3">
            <div class="metric-card">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <div class="text-success">
                        <i class="bi bi-building" style="font-size: 2rem;"></i>
                    </div>
                    <div class="text-end">
                        <h4 class="mb-0" id="institutionMembersCount">{{ stats.institution_members }}</h4>
                        <small class="text-muted">机构会员</small>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-2 col-md-4 mb-3">
            <div class="metric-card">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <div class="text-warning">
                        <i class="bi bi-graph-up" style="font-size: 2rem;"></i>
                    </div>
                    <div class="text-end">
                        <h4 class="mb-0" id="researchMembersCount">{{ stats.research_members }}</h4>
                        <small class="text-muted">科研会员</small>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-2 col-md-4 mb-3">
            <div class="metric-card">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <div class="text-info">
                        <i class="bi bi-currency-dollar" style="font-size: 2rem;"></i>
                    </div>
                    <div class="text-end">
                        <h4 class="mb-0" id="monthlyRevenue">¥{{ stats.monthly_revenue }}</h4>
                        <small class="text-muted">本月收入</small>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-2 col-md-4 mb-3">
            <div class="metric-card">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <div class="text-danger">
                        <i class="bi bi-exclamation-triangle" style="font-size: 2rem;"></i>
                    </div>
                    <div class="text-end">
                        <h4 class="mb-0" id="expiringSoonCount">{{ stats.expiring_soon }}</h4>
                        <small class="text-muted">即将到期</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- 功能按钮栏 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="mb-0">会员列表管理</h4>
        <div class="btn-group">
            <button class="btn btn-success me-2" data-bs-toggle="modal" data-bs-target="#addMemberModal">
                <i class="bi bi-person-plus me-1"></i>手动开通会员
            </button>
            <button class="btn btn-outline-primary me-2" onclick="exportMemberData()">
                <i class="bi bi-download me-1"></i>导出数据
            </button>
            <button class="btn btn-outline-warning" onclick="checkExpiringMembers()">
                <i class="bi bi-exclamation-triangle me-1"></i>到期提醒
            </button>
        </div>
    </div>

    <!-- 搜索筛选栏 -->
    <div class="search-filter-bar">
        <div class="row align-items-center">
            <div class="col-md-3">
                <div class="input-group">
                    <span class="input-group-text">
                        <i class="bi bi-search"></i>
                    </span>
                    <input type="text" class="form-control" id="searchInput" placeholder="搜索用户名、邮箱...">
                </div>
            </div>
            <div class="col-md-2">
                <select class="form-select" id="memberTypeFilter">
                    <option value="">全部类型</option>
                    <option value="basic">基础会员</option>
                    <option value="professional">专业会员</option>
                    <option value="institution">机构会员</option>
                    <option value="research">科研会员</option>
                </select>
            </div>
            <div class="col-md-2">
                <select class="form-select" id="statusFilter">
                    <option value="">全部状态</option>
                    <option value="active">有效</option>
                    <option value="expired">已过期</option>
                    <option value="cancelled">已取消</option>
                </select>
            </div>
            <div class="col-md-2">
                <select class="form-select" id="expiryFilter">
                    <option value="">到期时间</option>
                    <option value="expired">已过期</option>
                    <option value="7days">7天内到期</option>
                    <option value="30days">30天内到期</option>
                </select>
            </div>
            <div class="col-md-2">
                <button class="btn btn-outline-secondary w-100" onclick="applyFilters()">
                    <i class="bi bi-funnel me-1"></i>筛选
                </button>
            </div>
            <div class="col-md-1">
                <button class="btn btn-outline-primary w-100" onclick="resetFilters()">
                    <i class="bi bi-arrow-clockwise"></i>
                </button>
            </div>
        </div>
    </div>

    

    <!-- 会员列表 -->
    <div class="content-card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">会员列表</h5>
            <div class="d-flex align-items-center">
                <span class="text-muted me-3" id="totalMembersCount">共 {{ pagination.total }} 个会员</span>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-secondary" onclick="selectAllMembers()">
                        <i class="bi bi-check-all me-1"></i>全选
                    </button>
                    <button class="btn btn-outline-warning" onclick="batchRenewReminder()">
                        <i class="bi bi-bell me-1"></i>批量提醒
                    </button>
                </div>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>
                                <input type="checkbox" class="form-check-input" id="selectAll">
                            </th>
                            <th>用户信息</th>
                            <th>会员类型</th>
                            <th>开始时间</th>
                            <th>到期时间</th>
                            <th>剩余天数</th>
                            <th>支付金额</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="memberTableBody">
                        <!-- 会员数据将通过JavaScript加载 -->
                        <tr>
                            <td colspan="9" class="text-center py-4">
                                <div class="d-flex justify-content-center">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">加载中...</span>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="card-footer">
            <nav>
                <ul class="pagination pagination-sm justify-content-center mb-0" id="pagination">
                    <!-- 分页将通过JavaScript生成 -->
                </ul>
            </nav>
        </div>
    </div>
</div>

<!-- 手动开通会员模态框 -->
<div class="modal fade" id="addMemberModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">手动开通会员</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="addMemberForm">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">选择用户</label>
                                <select class="form-select" name="user_id" id="userSelect" required>
                                    <option value="">请选择用户</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">会员类型</label>
                                <select class="form-select" name="plan_type" required>
                                    <option value="">请选择会员类型</option>
                                    <option value="basic">基础会员 - 免费</option>
                                    <option value="professional">专业会员 - ¥299/月</option>
                                    <option value="institution">机构会员 - ¥999/月</option>
                                    <option value="research">科研会员 - ¥1999/月</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">开始日期</label>
                                <input type="date" class="form-control" name="start_date" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">有效期（天）</label>
                                <input type="number" class="form-control" name="duration_days" value="30" min="1" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">支付金额</label>
                                <input type="number" class="form-control" name="payment_amount" step="0.01" min="0">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">支付方式</label>
                                <select class="form-select" name="payment_method">
                                    <option value="manual">手动开通</option>
                                    <option value="alipay">支付宝</option>
                                    <option value="wechat">微信支付</option>
                                    <option value="bank_transfer">银行转账</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">备注</label>
                        <textarea class="form-control" name="remark" rows="3" placeholder="开通备注..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-success">开通会员</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑会员模态框 -->
<div class="modal fade" id="editMemberModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑会员信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editMemberForm">
                <div class="modal-body">
                    <input type="hidden" name="member_id" id="editMemberId">
                    <div class="mb-3">
                        <label class="form-label">会员类型</label>
                        <select class="form-select" name="plan_type" id="editPlanType" required>
                            <option value="basic">基础会员</option>
                            <option value="professional">专业会员</option>
                            <option value="institution">机构会员</option>
                            <option value="research">科研会员</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">到期时间</label>
                        <input type="date" class="form-control" name="end_date" id="editEndDate" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">状态</label>
                        <select class="form-select" name="status" id="editStatus" required>
                            <option value="active">有效</option>
                            <option value="expired">已过期</option>
                            <option value="cancelled">已取消</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存更改</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 到期提醒模态框 -->
<div class="modal fade" id="expiryReminderModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">会员到期提醒</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="expiringMembersList">
                    <!-- 即将到期的会员列表 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-warning" onclick="sendRenewalReminders()">
                    <i class="bi bi-send me-1"></i>发送提醒
                </button>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
// 当前页码和筛选参数
let currentPage = 1;
let currentFilters = {};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadMembers();
    loadUsers();
    
    // 绑定筛选事件
    document.getElementById('searchInput').addEventListener('input', debounce(applyFilters, 300));
    document.getElementById('memberTypeFilter').addEventListener('change', applyFilters);
    document.getElementById('statusFilter').addEventListener('change', applyFilters);
    document.getElementById('expiryFilter').addEventListener('change', applyFilters);
    
    // 绑定表单事件
    document.getElementById('addMemberForm').addEventListener('submit', handleAddMember);
    document.getElementById('editMemberForm').addEventListener('submit', handleEditMember);
    
    // 绑定全选事件
    document.getElementById('selectAll').addEventListener('change', function() {
        const memberCheckboxes = document.querySelectorAll('.member-checkbox');
        memberCheckboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });
});

// 加载会员列表
async function loadMembers(page = 1) {
    try {
        const params = new URLSearchParams({
            page: page,
            per_page: 20,
            ...currentFilters
        });
        
        const response = await fetch(`/api/admin/members?${params}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'include'  // 使用session认证
        });
        
        const data = await response.json();
        
        if (response.ok && data.success) {
            renderMemberTable(data.data.members);
            renderPagination(data.data.pagination);
            updateStats(data.data.stats);
        } else {
            showAlert(data.message || '加载会员列表失败', 'error');
        }
    } catch (error) {
        console.error('加载会员列表失败:', error);
        showAlert('加载会员列表失败，请检查网络连接', 'error');
    }
}

// 渲染会员表格
function renderMemberTable(members) {
    const tbody = document.getElementById('memberTableBody');
    tbody.innerHTML = '';
    
    members.forEach(member => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>
                <input type="checkbox" class="form-check-input member-checkbox" value="${member.id}">
            </td>
            <td>
                <div class="d-flex align-items-center">
                    <div class="user-avatar me-3">
                        <img src="/static/images/default-avatar-40.svg" alt="头像" class="rounded-circle">
                    </div>
                    <div>
                        <div class="fw-bold">${member.user.username}</div>
                        <small class="text-muted">${member.user.email}</small>
                    </div>
                </div>
            </td>
            <td>
                ${getMemberTypeBadge(member.plan_type)}
            </td>
            <td>
                <small>${formatDate(member.start_date)}</small>
            </td>
            <td>
                <small>${formatDate(member.end_date)}</small>
            </td>
            <td>
                ${getDaysRemainingBadge(member.days_remaining)}
            </td>
            <td>
                <span class="text-success">¥${member.payment_amount}</span>
            </td>
            <td>
                ${getStatusBadge(member.status)}
            </td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" onclick="editMember(${member.id})" title="编辑">
                        <i class="bi bi-pencil"></i>
                    </button>
                    <button class="btn btn-outline-success" onclick="renewMember(${member.id})" title="续费">
                        <i class="bi bi-arrow-repeat"></i>
                    </button>
                    <button class="btn btn-outline-info" onclick="viewMemberDetail(${member.id})" title="详情">
                        <i class="bi bi-eye"></i>
                    </button>
                </div>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 获取会员类型徽章
function getMemberTypeBadge(type) {
    const badges = {
        'basic': '<span class="badge bg-secondary">基础会员</span>',
        'professional': '<span class="badge bg-primary">专业会员</span>',
        'institution': '<span class="badge bg-success">机构会员</span>',
        'research': '<span class="badge bg-warning">科研会员</span>'
    };
    return badges[type] || '<span class="badge bg-light">未知</span>';
}

// 获取状态徽章
function getStatusBadge(status) {
    const badges = {
        'active': '<span class="badge bg-success">有效</span>',
        'expired': '<span class="badge bg-danger">已过期</span>',
        'cancelled': '<span class="badge bg-secondary">已取消</span>'
    };
    return badges[status] || '<span class="badge bg-light">未知</span>';
}

// 获取剩余天数徽章
function getDaysRemainingBadge(days) {
    if (days < 0) {
        return '<span class="badge bg-danger">已过期</span>';
    } else if (days <= 7) {
        return `<span class="badge bg-warning">${days}天</span>`;
    } else if (days <= 30) {
        return `<span class="badge bg-info">${days}天</span>`;
    } else {
        return `<span class="badge bg-success">${days}天</span>`;
    }
}

// 应用筛选
function applyFilters() {
    currentFilters = {
        search: document.getElementById('searchInput').value,
        member_type: document.getElementById('memberTypeFilter').value,
        status: document.getElementById('statusFilter').value,
        expiry: document.getElementById('expiryFilter').value
    };
    
    currentPage = 1;
    loadMembers(currentPage);
}

// 重置筛选
function resetFilters() {
    document.getElementById('searchInput').value = '';
    document.getElementById('memberTypeFilter').value = '';
    document.getElementById('statusFilter').value = '';
    document.getElementById('expiryFilter').value = '';
    
    currentFilters = {};
    currentPage = 1;
    loadMembers(currentPage);
}

// 加载用户列表（用于手动开通会员）
async function loadUsers() {
    try {
        const response = await fetch('/api/admin/users?all=true', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'include'
        });
        
        const data = await response.json();
        
        if (response.ok && data.success) {
            const userSelect = document.getElementById('userSelect');
            userSelect.innerHTML = '<option value="">请选择用户</option>';
            
            data.data.users.forEach(user => {
                const option = document.createElement('option');
                option.value = user.id;
                option.textContent = `${user.username} (${user.email})`;
                userSelect.appendChild(option);
            });
        }
    } catch (error) {
        console.error('加载用户列表失败:', error);
    }
}

// 处理手动开通会员
async function handleAddMember(e) {
    e.preventDefault();
    
    const formData = new FormData(e.target);
    const memberData = Object.fromEntries(formData);
    
    try {
        const response = await fetch('/api/admin/members', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'include',
            body: JSON.stringify(memberData)
        });
        
        const data = await response.json();
        
        if (response.ok && data.success) {
            showMemberSuccessToast('会员开通成功！', '新会员已成功添加到系统中');
            const modal = bootstrap.Modal.getInstance(document.getElementById('addMemberModal'));
            modal.hide();
            loadMembers(currentPage);
        } else {
            showAlert(data.message || '开通失败', 'error');
        }
    } catch (error) {
        console.error('开通会员失败:', error);
        showAlert('开通会员失败', 'error');
    }
}

// 编辑会员
async function editMember(memberId) {
    try {
        const response = await fetch(`/api/admin/members/${memberId}`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            const member = data.data;
            document.getElementById('editMemberId').value = member.id;
            document.getElementById('editPlanType').value = member.plan_type;
            document.getElementById('editEndDate').value = member.end_date;
            document.getElementById('editStatus').value = member.status;
            
            const modal = new bootstrap.Modal(document.getElementById('editMemberModal'));
            modal.show();
        }
    } catch (error) {
        console.error('获取会员信息失败:', error);
        showAlert('获取会员信息失败', 'error');
    }
}

// 处理编辑会员
async function handleEditMember(e) {
    e.preventDefault();
    
    const formData = new FormData(e.target);
    const memberData = Object.fromEntries(formData);
    const memberId = memberData.member_id;
    
    try {
        const response = await fetch(`/api/admin/members/${memberId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'include',
            body: JSON.stringify(memberData)
        });
        
        const data = await response.json();
        
        if (response.ok && data.success) {
            showMemberSuccessToast('会员信息更新成功！', '会员资料已成功更新');
            const modal = bootstrap.Modal.getInstance(document.getElementById('editMemberModal'));
            modal.hide();
            loadMembers(currentPage);
        } else {
            showAlert(data.message || '更新失败', 'error');
        }
    } catch (error) {
        console.error('更新会员信息失败:', error);
        showAlert('更新会员信息失败', 'error');
    }
}

// 检查即将到期的会员
async function checkExpiringMembers() {
    try {
        const response = await fetch('/api/admin/members/expiring', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'include'
        });
        
        const data = await response.json();
        
        if (response.ok && data.success) {
            renderExpiringMembers(data.data);
            const modal = new bootstrap.Modal(document.getElementById('expiryReminderModal'));
            modal.show();
        } else {
            showAlert(data.message || '获取即将到期会员失败', 'error');
        }
    } catch (error) {
        console.error('获取即将到期会员失败:', error);
        showAlert('获取即将到期会员失败', 'error');
    }
}

// 渲染即将到期的会员
function renderExpiringMembers(members) {
    const container = document.getElementById('expiringMembersList');
    
    if (members.length === 0) {
        container.innerHTML = '<div class="text-center text-muted py-4">暂无即将到期的会员</div>';
        return;
    }
    
    const html = members.map(member => `
        <div class="card mb-2">
            <div class="card-body py-2">
                <div class="row align-items-center">
                    <div class="col-md-4">
                        <strong>${member.user.username}</strong><br>
                        <small class="text-muted">${member.user.email}</small>
                    </div>
                    <div class="col-md-3">
                        ${getMemberTypeBadge(member.plan_type)}
                    </div>
                    <div class="col-md-3">
                        <small>到期时间: ${formatDate(member.end_date)}</small><br>
                        ${getDaysRemainingBadge(member.days_remaining)}
                    </div>
                    <div class="col-md-2">
                        <input type="checkbox" class="form-check-input reminder-checkbox" value="${member.id}">
                    </div>
                </div>
            </div>
        </div>
    `).join('');
    
    container.innerHTML = html;
}

// 发送续费提醒（从到期提醒模态框）
async function sendRenewalReminders() {
    const checkedMembers = Array.from(document.querySelectorAll('.reminder-checkbox:checked'))
        .map(cb => cb.value);
    
    if (checkedMembers.length === 0) {
        showAlert('请选择要提醒的会员', 'warning');
        return;
    }
    
    try {
        const response = await fetch('/api/admin/members/renewal-reminder', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'include',
            body: JSON.stringify({ member_ids: checkedMembers })
        });
        
        const data = await response.json();
        
        if (response.ok && data.success) {
            showMemberSuccessToast('续费提醒发送成功！', `已成功向 ${checkedMembers.length} 位会员发送续费提醒`);
            const modal = bootstrap.Modal.getInstance(document.getElementById('expiryReminderModal'));
            modal.hide();
        } else {
            showAlert(data.message || '发送失败', 'error');
        }
    } catch (error) {
        console.error('发送续费提醒失败', error);
        showAlert('发送续费提醒失败', 'error');
    }
}

// 工具函数
function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function showAlert(message, type = 'info') {
    // 实现消息提示功能
    const alertClass = type === 'error' ? 'alert-danger' : 
                      type === 'success' ? 'alert-success' : 
                      type === 'warning' ? 'alert-warning' : 'alert-info';
    
    const alert = document.createElement('div');
    alert.className = `alert ${alertClass} alert-dismissible fade show position-fixed`;
    alert.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alert);
    
    setTimeout(() => {
        if (alert.parentNode) {
            alert.parentNode.removeChild(alert);
        }
    }, 5000);
}

// 渲染分页
function renderPagination(pagination) {
    const paginationEl = document.getElementById('pagination');
    if (!pagination || pagination.pages <= 1) {
        paginationEl.innerHTML = '';
        return;
    }
    
    let html = '';
    
    // 上一页
    if (pagination.has_prev) {
        html += `<li class="page-item">
            <a class="page-link" href="#" onclick="loadMembers(${pagination.page - 1})">上一页</a>
        </li>`;
    }
    
    // 页码
    for (let i = 1; i <= pagination.pages; i++) {
        if (i === pagination.page) {
            html += `<li class="page-item active">
                <span class="page-link">${i}</span>
            </li>`;
        } else {
            html += `<li class="page-item">
                <a class="page-link" href="#" onclick="loadMembers(${i})">${i}</a>
            </li>`;
        }
    }
    
    // 下一页
    if (pagination.has_next) {
        html += `<li class="page-item">
            <a class="page-link" href="#" onclick="loadMembers(${pagination.page + 1})">下一页</a>
        </li>`;
    }
    
    paginationEl.innerHTML = html;
}

// 更新统计数据
function updateStats(stats) {
    // 这里可以更新页面上的统计数据
    console.log('Stats updated:', stats);
    document.getElementById('basicMembersCount').textContent = stats.basic_members;
    document.getElementById('professionalMembersCount').textContent = stats.professional_members;
    document.getElementById('institutionMembersCount').textContent = stats.institution_members;
    document.getElementById('researchMembersCount').textContent = stats.research_members;
    document.getElementById('monthlyRevenue').textContent = `¥${stats.monthly_revenue}`;
    document.getElementById('expiringSoonCount').textContent = stats.expiring_soon;
}

// 导出数据功能
async function exportMemberData() {
    try {
        const response = await fetch('/api/admin/members/export', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'include'
        });
        
        if (response.ok) {
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `会员数据_${new Date().toISOString().split('T')[0]}.xlsx`;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
            showMemberSuccessToast('数据导出成功！', '会员数据已生成Excel文件并下载');
        } else {
            showAlert('数据导出失败', 'error');
        }
    } catch (error) {
        console.error('导出数据失败:', error);
        showAlert('数据导出失败', 'error');
    }
}

// 编辑会员
async function editMember(memberId) {
    try {
        const response = await fetch(`/api/admin/members/${memberId}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'include'
        });
        
        const data = await response.json();
        
        if (response.ok && data.success) {
            const member = data.data;
            
            // 填充编辑表单
            document.getElementById('editMemberId').value = member.id;
            document.getElementById('editPlanType').value = member.plan_type;
            document.getElementById('editEndDate').value = member.end_date;
            document.getElementById('editStatus').value = member.status;
            
            // 显示编辑模态框
            const modal = new bootstrap.Modal(document.getElementById('editMemberModal'));
            modal.show();
        } else {
            showAlert(data.message || '获取会员信息失败', 'error');
        }
    } catch (error) {
        console.error('获取会员信息失败:', error);
        showAlert('获取会员信息失败', 'error');
    }
}

// 查看会员详情
async function viewMemberDetail(memberId) {
    try {
        const response = await fetch(`/api/admin/members/${memberId}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'include'
        });
        
        const data = await response.json();
        
        if (response.ok && data.success) {
            const member = data.data;
            
            // 显示会员详情（这里可以创建一个详情模态框）
            alert(`会员详情：\n用户：${member.user.username}\n类型：${member.plan_type}\n状态：${member.status}\n到期时间：${member.end_date}`);
        } else {
            showAlert(data.message || '获取会员详情失败', 'error');
        }
    } catch (error) {
        console.error('获取会员详情失败:', error);
        showAlert('获取会员详情失败', 'error');
    }
}

// 续费会员
async function renewMember(memberId) {
    if (!confirm('确定要续费该会员吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/admin/members/${memberId}/renew`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'include',
            body: JSON.stringify({ duration_days: 30 })
        });
        
        const data = await response.json();
        
        if (response.ok && data.success) {
            showMemberSuccessToast('续费成功！', '会员有效期已延长30天');
            loadMembers(currentPage);
        } else {
            showAlert(data.message || '续费失败', 'error');
        }
    } catch (error) {
        console.error('续费失败:', error);
        showAlert('续费失败', 'error');
    }
}

// 全选/取消全选
function selectAllMembers() {
    const selectAllCheckbox = document.getElementById('selectAll');
    const memberCheckboxes = document.querySelectorAll('.member-checkbox');
    
    memberCheckboxes.forEach(checkbox => {
        checkbox.checked = selectAllCheckbox.checked;
    });
}

// 批量续费提醒
async function batchRenewReminder() {
    const checkedMembers = Array.from(document.querySelectorAll('.member-checkbox:checked'));
    
    if (checkedMembers.length === 0) {
        showAlert('请先选择要提醒的会员', 'warning');
        return;
    }
    
    if (confirm(`确定要向 ${checkedMembers.length} 个会员发送续费提醒吗？`)) {
        const memberIds = checkedMembers.map(cb => cb.value);
        
        try {
            const response = await fetch('/api/admin/members/renewal-reminder', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                credentials: 'include',
                body: JSON.stringify({ member_ids: memberIds })
            });
            
            const data = await response.json();
            
            if (response.ok && data.success) {
                showMemberSuccessToast('续费提醒发送成功！', `已成功向 ${checkedMembers.length} 位会员发送续费提醒`);
            } else {
                showAlert(data.message || '发送失败', 'error');
            }
        } catch (error) {
            console.error('发送续费提醒失败:', error);
            showAlert('发送续费提醒失败', 'error');
        }
    }
}

// 美化的会员管理成功提示
function showMemberSuccessToast(title, message, duration = 5000) {
    console.log('🎉 会员管理成功提示:', title, message);
    
    // 创建Toast容器（如果不存在）
    let toastContainer = document.getElementById('member-toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.id = 'member-toast-container';
        toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
        toastContainer.style.zIndex = '9999';
        document.body.appendChild(toastContainer);
    }
    
    const toastId = 'member-success-toast-' + Date.now();
    
    // 创建会员管理成功Toast
    const toastHTML = `
        <div id="${toastId}" class="toast border-0 shadow-lg" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="${duration}" style="background: linear-gradient(135deg, #007bff 0%, #6610f2 100%);">
            <div class="d-flex align-items-start text-white p-3">
                <div class="me-3">
                    <div class="member-success-icon">
                        <i class="bi bi-people-fill fs-3"></i>
                    </div>
                </div>
                <div class="flex-grow-1">
                    <div class="fw-bold mb-1">${title}</div>
                    <div class="small opacity-90">${message}</div>
                </div>
                <button type="button" class="btn-close btn-close-white ms-2" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="member-progress-bar"></div>
        </div>
    `;
    
    // 添加CSS动画样式（如果不存在）
    if (!document.getElementById('member-toast-styles')) {
        const styles = document.createElement('style');
        styles.id = 'member-toast-styles';
        styles.textContent = `
            .member-success-icon {
                animation: memberSuccessBounce 0.6s ease-out;
            }
            
            @keyframes memberSuccessBounce {
                0% { transform: scale(0.4) rotate(-10deg); opacity: 0; }
                50% { transform: scale(1.1) rotate(5deg); }
                100% { transform: scale(1) rotate(0deg); opacity: 1; }
            }
            
            .member-progress-bar {
                height: 3px;
                background: rgba(255, 255, 255, 0.3);
                animation: memberProgressBar ${duration}ms linear;
            }
            
            @keyframes memberProgressBar {
                from { width: 100%; }
                to { width: 0%; }
            }
            
            .member-star {
                position: fixed;
                width: 12px;
                height: 12px;
                background: #ffd700;
                clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);
                animation: memberStarFall 3s ease-out forwards;
                pointer-events: none;
                z-index: 10000;
            }
            
            @keyframes memberStarFall {
                0% {
                    transform: translateY(-100vh) rotate(0deg);
                    opacity: 1;
                }
                100% {
                    transform: translateY(100vh) rotate(360deg);
                    opacity: 0;
                }
            }
        `;
        document.head.appendChild(styles);
    }
    
    // 添加到容器
    toastContainer.insertAdjacentHTML('afterbegin', toastHTML);
    
    // 初始化并显示Toast
    const toastElement = document.getElementById(toastId);
    const toast = new bootstrap.Toast(toastElement, {
        animation: true,
        autohide: true,
        delay: duration
    });
    
    // 显示Toast
    toast.show();
    
    // 添加会员管理庆祝效果
    createMemberStars();
    
    // 自动移除DOM元素
    toastElement.addEventListener('hidden.bs.toast', function() {
        toastElement.remove();
        
        // 如果容器为空，也移除容器
        if (toastContainer.children.length === 0) {
            toastContainer.remove();
        }
    });
    
    return toast;
}

// 会员管理庆祝效果
function createMemberStars() {
    const starCount = 8;
    
    for (let i = 0; i < starCount; i++) {
        const star = document.createElement('div');
        star.className = 'member-star';
        star.style.left = (Math.random() * 100) + 'vw';
        star.style.animationDelay = (Math.random() * 2) + 's';
        star.style.animationDuration = (Math.random() * 2 + 2) + 's';
        
        document.body.appendChild(star);
        
        // 清理
        setTimeout(() => {
            star.remove();
        }, 4000);
    }
}
</script>
{% endblock %} 